<template>
  <van-nav-bar
  title="地址列表"
  left-text="返回"
  left-arrow
  @click-left="onClickLeft"
/>
  <div>
    <van-address-list
      v-model="locationStore.chosenAddressId"
      :list="locationStore.locationsList"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @select="onSelect"
    >
  <template #item-bottom="item">
    <div class="item-bottom">
      <van-button
        size="small"
        type="danger"
        @click.stop="onDelete(item.id)"
      >删除</van-button>
    </div>
  </template>
  </van-address-list>
  </div>
  
</template>

<script setup>
import { useLocationStore } from "../../store/location";
const locationStore = useLocationStore();
import {  showSuccessToast, showConfirmDialog, showFailToast } from "vant";
import router from '../../router'
// 点击返回按钮
const onClickLeft = () => {
  router.back();
}
const onAdd = () => {
  // 跳转到添加地址页
  router.push('/locationEdit');
};
const onEdit = (id) => {
  // 跳转到编辑地址页  传入id参数
  router.push({ path: '/locationEdit', query: { id } });
};
// 切换默认地址
const onSelect = (item) => {
  // 如果不是默认地址则替换
  if (!item.isDefault) {
    locationStore.changeDefault(item.id);
    showSuccessToast('默认地址已切换')
  }
}
const onDelete = (id) => { 
    showConfirmDialog({
  title: '删除地址',
  message:
    '您确认要删除此地址么?',
})
  .then(() => {
    // 确认删除
    locationStore.deleteLocation(id);
    showSuccessToast('地址删除成功');
  })
  .catch(() => {
    // 取消删除
    showFailToast('取消删除')
  })
  }


</script>

<style scoped lang="scss">
.item-bottom {
  text-align: right;
}

</style>
